<template>
    <div class="shoppingCart">
        <!-- 购物车头部 -->
        <div class="cart-header">
            <div class="cart-header-content">
                <p>
                    <i class="el-icon-shopping-cart-full" style="color:#ff6700; font-weight: 600;"></i>
                    我的购物车
                </p>
                <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
            </div>
        </div>
        <!-- 购物车头部END -->

        <!-- 购物车主要内容区 -->
        <div class="content" v-if="productNum > 0">
            <ul>
                <!-- 购物车表头 -->
                <li class="header">
                    <div class="pro-check">
                        <!--只要有一件商品未勾选,全选按钮就不能勾选-->
                        <el-checkbox v-model="checkAll" @change="handleCheckAllChange($event)">全选</el-checkbox>
                    </div>
                    <div class="pro-img"></div>
                    <div class="pro-name">商品名称</div>
                    <div class="pro-price">单价</div>
                    <div class="pro-num">数量</div>
                    <div class="pro-total">小计</div>
                    <div class="pro-action">操作</div>
                </li>
                <!-- 购物车表头END -->

                <!-- 购物车列表 -->
                <li class="product-list" v-for="(item,index) in cartData" :key="index">
                    <div class="pro-check">
                        <el-checkbox :value="item.checked" @change="checkChange($event, index, item.id)"></el-checkbox>
                    </div>
                    <div class="pro-img">
                        <img :src="item.head_img_url" alt="item.name">
                    </div>
                    <div class="pro-name">
                        <router-link :to="'/detail/' + item.id" :title="item.name">{{item.name}}</router-link>
                    </div>
                    <div class="pro-price">{{item.price}}元</div>
                    <div class="pro-num">
                        <el-input-number
                                size="small"
                                v-model="item.num"
                                :min="1"
                                :max="item.stock"
                                @change="cartNumChange($event,index,item.id)"
                        ></el-input-number>
                    </div>
                    <div class="pro-total pro-total-in">{{item.price * item.num}}元</div>
                    <div class="pro-action">
                        <el-popover placement="right">
                            <p>确定删除吗？</p>
                            <div style="text-align: right; margin: 10px 0 0">
                                <el-button
                                        type="primary"
                                        size="mini"
                                        @click="deleteProduct($event, item.id)"
                                >确定</el-button>
                            </div>
                            <i class="el-icon-error" slot="reference" style="font-size: 18px;"></i>
                        </el-popover>
                    </div>
                </li>
                <!-- 购物车列表END -->
            </ul>
            <div style="height:20px;background-color: #f5f5f5"></div>
            <!-- 购物车底部导航条 -->
            <div class="cart-bar">
                <div class="cart-bar-left">
          <span>
              <!--清空购物车-->
              <el-popover placement="right">
                            <p>你确定要清空购物车吗？</p>
                            <div style="text-align: right; margin: 10px 0 0">
                                 <el-button type="primary" size="mini" @click="clearCartProduct">确定</el-button>
                            </div>
                            <el-button type="danger" slot="reference">清空购物车</el-button>
              </el-popover>
          </span>
                    <span class="sep">|</span>
                    <span class="cart-total">
            共
            <span class="cart-total-num">{{productNum}}</span> 件商品，已选择
            <span class="cart-total-num">{{selectProductNum}}</span> 件
          </span>
                </div>
                <div class="cart-bar-right">
          <span>
            <span class="total-price-title">合计：</span>
            <span class="total-price">{{total}}元</span>
          </span>
            <router-link :to="selectProductNum > 0 ? '/confirmOrder' : ''">
                <!--结算图标商品大于0高亮 否则不能结算-->
                <div :class="selectProductNum > 0 ? 'btn-primary' : 'btn-primary-disabled'">去结算</div>
            </router-link>
                </div>
            </div>
            <!-- 购物车底部导航条END -->
        </div>
        <!-- 购物车主要内容区END -->

        <!-- 购物车为空的时候显示的内容 -->
        <div v-if="productNum == 0" class="cart-empty">
            <div class="empty">
                <h2>您的购物车还是空的！</h2>
                <p>快去购物吧！</p>
            </div>
        </div>
        <!-- 购物车为空的时候显示的内容END -->


    </div>
</template>
<script>
    export default {
        data() {
            return {
                total: null, // 合计 (已选择商品总价格)
                userInfo: {}, // 用户信息
                cartData: [], // 购物车数据
                productNum: null, // 购物车商品总数量
                selectProductNum: null, // 已选择商品总数量
                checkAll: true, // 全选按钮, 默认全选
            };
        },
        methods: {
            // 初始化用户信息
            initUserInfo() {
                let json_userInfo = localStorage.getItem('userInfo');
                let userInfo = JSON.parse(json_userInfo);
                if (json_userInfo == null) {
                    // 没有登录
                    this.errorNotify('用户未登录','用户未登录');
                }
                else {
                    this.userInfo = userInfo;
                    this.getCartData();
                }
            },
            // 获取购物车数据
            getCartData() {
                let userInfo = JSON.parse(JSON.stringify(this.userInfo))
                this.$axios({
                    method: 'get',
                    url: this.baseUrl + '/api/v1/cart/list',
                    headers: {
                        'access-token': userInfo.token,
                        'telephone': userInfo.telephone
                    }
                }).then(response => {
                    let result = response.data;
                    this._getCartTotalPrice(result.data);  // 计算商品总价格
                    this._getCartProductNum(result.data); // 计算商品总数量
                    this._getSelectProductNum(result.data); // 计算选择商品数量
                    // 保存缓存解决刷新vuex数据为0的问题
                    localStorage.setItem('productNum',this.productNum);
                    localStorage.setItem('selectProductNum',this.selectProductNum);
                    localStorage.setItem('productTotalPrice',this.total);
                    this.$store.commit('setCartProductNum', this.productNum); //购物车商品总数量
                    this.$store.commit('setCartSelectProductNum', this.selectProductNum); //选择商品
                    this.$store.commit('setCartProductTotalPrice', this.total); // 商品总价
                    this.cartData = result.data;
                    // 全选按钮只有勾选了全部商品才会勾选
                    if (this.selectProductNum != this.productNum) {
                        this.checkAll = false;
                    }
                    else {
                        this.checkAll = true;
                    }

                }).catch(error => {
                    console.log(error.response)
                })
            },
            // 购物车数量改变 currentValue 当前input数量
            cartNumChange(currentValue, key, productID) {
                let userInfo = JSON.parse(JSON.stringify(this.userInfo))
                // 通过后端, 更新当前商品数量
                this.$axios({
                    method: 'post',
                    url: this.baseUrl + '/api/v1/cart/updateCartProductNum',
                    data: {
                        'product_id': productID,
                        'num': currentValue
                    },
                    headers: {
                        'access-token': userInfo.token,
                        'telephone': userInfo.telephone
                    }
                }).then(response => {
                    let result = response.data;
                    if (result.status == 200) {
                        this.notify(result.message, result.message);
                    }
                    this.getCartData(); // 数据已经改变, 数量改变,总价格都会改变

                }).catch(error => {
                    console.log(error.response)
                })
            },
            // 改变CheckBox状态 checked 状态 product_id 商品id
            checkChange(checked, index, product_id) {
                let userInfo = JSON.parse(JSON.stringify(this.userInfo))
                this.$axios({
                    method: 'post',
                    url: this.baseUrl + '/api/v1/cart/updateCartProductChecked',
                    headers: {
                        'access-token': userInfo.token,
                        'telephone': userInfo.telephone
                    },
                    data: {
                        'product_id': product_id,
                        'checked': checked
                    }
                }).then(response => {
                    if (response.data.status == 200) {
                        // 更新列表数据
                        this.getCartData();
                    }

                }).catch(error => {
                    console.log(error.response)
                })


            },
            // 改变全选按钮事件
            handleCheckAllChange(checked) {
                // 通过后端, 改变redis数据库中所有商品checked值
                // 当checked 为true, 表示需要全选, checked全部为true
                // 当checked为false,表示不需要全选,checked全部为false
                let userInfo = JSON.parse(JSON.stringify(this.userInfo))
                // 通过后端, 更新当前商品数量
                this.$axios({
                    method: 'post',
                    url: this.baseUrl + '/api/v1/cart/updateCartProductAllChecked',
                    data: {
                        'checked': checked
                    },
                    headers: {
                        'access-token': userInfo.token,
                        'telephone': userInfo.telephone
                    }
                }).then(response => {
                    if (response.data.status == 200) {
                        this.getCartData(); // 重新加载数据
                    }
                }).catch(error => {
                    console.log(error.response)
                })
            },
            // 删除一个购物车商品
            deleteProduct($event, product_id) {
                let userInfo = JSON.parse(JSON.stringify(this.userInfo))
                // 通过后端, 更新当前商品数量
                this.$axios({
                    method: 'get',
                    url: this.baseUrl + '/api/v1/cart/del/' + product_id,
                    headers: {
                        'access-token': userInfo.token,
                        'telephone': userInfo.telephone
                    }
                }).then(response => {
                    if (response.data.status == 200) {
                        this.notify(response.data.message, response.data.message);
                        this.getCartData();
                    }
                }).catch(error => {
                    console.log(error.response)
                })

            },
            // 清空购物车商品
            clearCartProduct() {
                let userInfo = JSON.parse(JSON.stringify(this.userInfo))
                this.$axios({
                    method: 'get',
                    url: this.baseUrl + '/api/v1/cart/delAll',
                    headers: {
                        'access-token': userInfo.token,
                        'telephone': userInfo.telephone
                    }
                }).then(response => {
                    if (response.data.status == 200) {
                        this.notify(response.data.message, response.data.message);
                        this.getCartData();
                    }
                }).catch(error => {
                    console.log(error.response)
                })
            },
            // 提示信息 title string 标题 message string 提示信息
            notify(title, message) {
                const h = this.$createElement;
                this.$notify({
                    title: title,
                    message: h('i', {style: 'color: teal'}, message)
                });
            },
            // 错误提示
            errorNotify(title, message) {
                const h = this.$createElement;
                this.$notify({
                    title: title,
                    type: "error",
                    duration: 2000,
                    message: h('i', {style: 'color: red'}, message)
                });
            },
            // 计算(已选择的商品)购物车总价格
            _getCartTotalPrice(products) {
                let totalPrice = 0;
                products.forEach(item => {
                    if (item.checked == true) {
                        totalPrice += item.num * item.price;
                    }
                })
                this.total = totalPrice;
            },
            // 获取购物车一共商品的总数量
            _getCartProductNum(products) {
                let productNum = 0;
                products.forEach(item => {
                    productNum += item.num;
                })
                this.productNum = productNum;
            },
            // 计算已选择商品的总数量
            _getSelectProductNum(products) {
                let selectNum = 0;
                products.forEach(item => {
                    if (item.checked == true) {
                        selectNum += item.num;
                    }
                })
                this.selectProductNum = selectNum;
            }
        },
        created() {

        },
        activated() {
            this.initUserInfo();
        }
    };
</script>
<style scoped>
    .shoppingCart {
        background-color: #f5f5f5;
        padding-bottom: 20px;
    }
    /* 购物车头部CSS */
    .shoppingCart .cart-header {
        height: 64px;
        border-bottom: 2px solid #ff6700;
        background-color: #fff;
        margin-bottom: 20px;
    }
    .shoppingCart .cart-header .cart-header-content {
        width: 1225px;
        margin: 0 auto;
    }
    .shoppingCart .cart-header p {
        font-size: 28px;
        line-height: 58px;
        float: left;
        font-weight: normal;
        color: #424242;
    }
    .shoppingCart .cart-header span {
        color: #757575;
        font-size: 12px;
        float: left;
        height: 20px;
        line-height: 20px;
        margin-top: 30px;
        margin-left: 15px;
    }
    /* 购物车头部CSS END */

    /* 购物车主要内容区CSS */
    .shoppingCart .content {
        width: 1225px;
        margin: 0 auto;
        background-color: #fff;
    }

    .shoppingCart .content ul {
        background-color: #fff;
        color: #424242;
        line-height: 85px;
    }
    /* 购物车表头及CSS */
    .shoppingCart .content ul .header {
        height: 85px;
        padding-right: 26px;
        color: #424242;
    }
    .shoppingCart .content ul .product-list {
        height: 85px;
        padding: 15px 26px 15px 0;
        border-top: 1px solid #e0e0e0;
    }
    .shoppingCart .content ul .pro-check {
        float: left;
        height: 85px;
        width: 110px;
    }
    .shoppingCart .content ul .pro-check .el-checkbox {
        font-size: 16px;
        margin-left: 24px;
    }
    .shoppingCart .content ul .pro-img {
        float: left;
        height: 85px;
        width: 120px;
    }
    .shoppingCart .content ul .pro-img img {
        height: 80px;
        width: 80px;
    }
    .shoppingCart .content ul .pro-name {
        float: left;
        width: 380px;
    }
    .shoppingCart .content ul .pro-name a {
        color: #424242;
    }
    .shoppingCart .content ul .pro-name a:hover {
        color: #ff6700;
    }
    .shoppingCart .content ul .pro-price {
        float: left;
        width: 140px;
        padding-right: 18px;
        text-align: center;
    }
    .shoppingCart .content ul .pro-num {
        float: left;
        width: 150px;
        text-align: center;
    }
    .shoppingCart .content ul .pro-total {
        float: left;
        width: 120px;
        padding-right: 81px;
        text-align: right;
    }
    .shoppingCart .content ul .pro-total-in {
        color: #ff6700;
    }
    .shoppingCart .content ul .pro-action {
        float: left;
        width: 80px;
        text-align: center;
    }
    .shoppingCart .content ul .pro-action i:hover {
        color: #ff6700;
    }
    /* 购物车表头及CSS END */

    /* 购物车底部导航条CSS */
    .shoppingCart .cart-bar {
        width: 1225px;
        height: 50px;
        line-height: 50px;
        background-color: #fff;
    }
    .shoppingCart .cart-bar .cart-bar-left {
        float: left;
    }
    .shoppingCart .cart-bar .cart-bar-left a {
        line-height: 50px;
        margin-left: 32px;
        color: #757575;
    }
    .shoppingCart .cart-bar .cart-bar-left a:hover {
        color: #ff6700;
    }
    .shoppingCart .cart-bar .cart-bar-left .sep {
        color: #eee;
        margin: 0 20px;
    }
    .shoppingCart .cart-bar .cart-bar-left .cart-total {
        color: #757575;
    }
    .shoppingCart .cart-bar .cart-bar-left .cart-total-num {
        color: #ff6700;
    }
    .shoppingCart .cart-bar .cart-bar-right {
        float: right;
    }
    .shoppingCart .cart-bar .cart-bar-right .total-price-title {
        color: #ff6700;
        font-size: 14px;
    }
    .shoppingCart .cart-bar .cart-bar-right .total-price {
        color: #ff6700;
        font-size: 30px;
    }
    .shoppingCart .cart-bar .cart-bar-right .btn-primary {
        float: right;
        width: 200px;
        text-align: center;
        font-size: 18px;
        margin-left: 50px;
        background: #ff6700;
        color: #fff;
    }
    .shoppingCart .cart-bar .cart-bar-right .btn-primary-disabled {
        float: right;
        width: 200px;
        text-align: center;
        font-size: 18px;
        margin-left: 50px;
        background: #e0e0e0;
        color: #b0b0b0;
    }
    .shoppingCart .cart-bar .cart-bar-right .btn-primary:hover {
        background-color: #f25807;
    }
    /* 购物车底部导航条CSS END */
    /* 购物车主要内容区CSS END */

    /* 购物车为空的时候显示的内容CSS */
    .shoppingCart .cart-empty {
        width: 1225px;
        margin: 0 auto;
    }
    .shoppingCart .cart-empty .empty {
        height: 300px;
        padding: 0 0 130px 558px;
        margin: 65px 0 0;
        background: url(../assets/imgs/cart-empty.png) no-repeat 124px 0;
        color: #b0b0b0;
        overflow: hidden;
    }
    .shoppingCart .cart-empty .empty h2 {
        margin: 70px 0 15px;
        font-size: 36px;
    }
    .shoppingCart .cart-empty .empty p {
        margin: 0 0 20px;
        font-size: 20px;
    }
    /* 购物车为空的时候显示的内容CSS END */
</style>
